<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form-model
        ref="form"
        :model="model"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 20 }"
        :rules="validatorRules"
        slot="detail">

        <a-form-model-item label="标题" prop="title">
          <a-input v-model="model.title" placeholder="请输入标题" :maxLength="100" :disabled="formDisabled" />
        </a-form-model-item>
        <a-row :gutter="24">
          <a-col :span="12" :style="leftPadding">
            <a-form-model-item label="类别" prop="noticeCategory">
              <j-dict-select-tag
                v-model="model.noticeCategory"
                :disabled="formDisabled"
                dictCode="notice_category"
                placeholder="请选择" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" :style="rightPadding">
            <a-form-model-item
              label="发文密级"
              prop="intensiveType"
              :labelCol="{ span: 4 }"
            >
              <j-dict-select-tag
                style="width: 95%;"
                v-model="model.intensiveType"
                :disabled="formDisabled"
                dictCode="document_intensive_type"
                placeholder="请选择发文密级"
                @input="handleIntensiveInput" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" :style="leftPadding">
            <a-form-model-item label="发布人">
              <a-input :value="model.handlerId_dictText || userInfo().realname" placeholder="请输入" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="内容" prop="content">
          <j-editor v-model="model.content" :disabled="formDisabled" />
        </a-form-model-item>
        <!-- <a-form-model-item label="图片上传" prop="pics">
              <j-upload v-model="model.pics" :number="10" disabled v-if='formDisabled' :showDownLoadBtn="false"/>
              <j-image-upload v-model="model.pics" :number="10" v-else/>
            </a-form-model-item> -->
        <a-form-model-item label="附件" prop="attachments">
          <j-upload
            v-model="model.attachments"
            :number="10"
            :disabled="formDisabled"
            :filePdf="true"
            v-if="!formDisabled" />

          <div v-else>
            <a-list size="small" bordered :data-source="attachmentsComp">
              <a-list-item slot="renderItem" slot-scope="item">
                <a @click="showModal(item)">{{ item }}</a>
              </a-list-item>
            </a-list>
          </div>

        </a-form-model-item>
        <a-form-model-item :label="`${formDisabled?'':'选择'}接收人`" v-if="signStatus!=null">

          <a-button type="primary" @click="acceptClick">{{ selectEmpList.length==0?'我未选择':'我已选择' }}</a-button>

        </a-form-model-item>

      </a-form-model>
    </j-form-container>
    <teamChoose
      ref="team"
      @sure="sureTeam"
      :selectEmpList="selectEmpList"
      :disabled="formDisabled"
      :intensiveType="model.intensiveType" />
    <process-config-modal ref="processConfig" @ok="handleSuccess"></process-config-modal>
    <a-modal
      :title="!model.intensiveType || model.intensiveType == 'ordinary' ? '请选择预览或下载' : '请选择预览'"
      :visible="prebtnVisible"
      :footer="null"
      @cancel="prebtnVisible = false, fileUrl=''"
      :width="240">
      <div style="text-align: center;">
        <a-button shape="circle" icon="search" @click="showFile(fileUrl)" :loading="modalShowLoading" />
        <template v-if="!model.intensiveType || model.intensiveType == 'ordinary'">
          <a-divider type="vertical" />
          <a-button shape="circle" icon="download" @click="downloadFile" :loading="modalLoading" />
        </template>
      </div>
    </a-modal>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { mapGetters } from 'vuex'
import teamChoose from '../comp/teamChooseModal'
import ProcessConfigModal from '@/views/scy/components/ProcessConfigModal'
import PreviewPdf from '@/utils/previewPdf'
import { axios } from '@/utils/request'
import { PDFDocument } from 'pdf-lib'
export default {
  name: 'NoticeForm',
  components: {
    teamChoose,
    ProcessConfigModal
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data () {
    return {
      model: {
      },
      modalLoading: false, // 弹窗下载loading
      modalShowLoading: false, // 弹窗预览loading
      prebtnVisible: false, // 弹窗选择
      fileUrl: '',
      wSrc: '',
      selectEmpList: [], // 选择人员列表
      confirmLoading: false,
      validatorRules: {
        title: [
          { required: true, message: '请输入标题!' }
        ],
        noticeCategory: [
          { required: true, message: '请选择类别!' }
        ],
        intensiveType: [
          { required: true, message: '请选择发文密级!' }
        ]
      },
      url: {
        add: '/api/erp/publishNotice/add',
        edit: '/api/erp/publishNotice/edit',
        queryPageById: '/api/erp/publishNotice/queryPageById',
        findEmpUserSelect: '/api/erp/publishNotice/findEmpUserSelect',
        read: '/api/erp/publishNotice/read'
      },
      flowCode: 'onl_erp_publish_notice',
      formUrl: '/erp/docManage/modules/noticeForm',
      beanName: 'erpPublishNoticeServiceImpl',
      processId: '',
      progress: '',
      formUrlMobile: '/pages/synergy/noticeAnnounceList',
      signStatus: ''
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    leftPadding() {
      if (this.formBpm === true) {
        return { paddingLeft: '140px' }
      } else {
        return { paddingLeft: this.formDisabled ? '107px' : '96px' }
      }
    },
    rightPadding() {
      if (this.formBpm === true) {
        return { paddingRight: '50px' }
      } else {
        return { paddingRight: this.formDisabled ? '41px' : '38px' }
      }
    },
    attachmentsComp() {
      let list = []
      if (this.model.attachments) {
        list = this.model.attachments.split(',')
      }
      return list
    }
  },
  created () {
    this.showFlowData()
  },
  methods: {
    ...mapGetters(['userInfo']),
    // 选择密级
    handleIntensiveInput (value) {
      // 清空“选择接收人”
      this.selectEmpList = []
    },
    // 添加or编辑
    async addOrEdit (record) {
      this.model = {}
      if (record) {
        this.progress = record.progress
        this.signStatus = record.signStatus
        this.confirmLoading = true
        let rr = await getAction(this.url.queryPageById, { id: record.id })
        if (rr.success) {
          this.model = rr.result.records[0]
        }
        this.confirmLoading = false
        this.getSelectUsers(record.id)
      } else {
        this.selectEmpList = []
      }
    },
    // 获取选中的接收人
    async getSelectUsers(id) {
      let params = {
          noticeId: id,
          pageNo: 1,
          pageSize: -1,
          empId: this.formBpm ? this.model.handlerId : this.userInfo().empId
        }
        let res = await getAction(this.url.findEmpUserSelect, params)
        if (res.success) {
          this.selectEmpList = res.result.records || []
        } else {
          this.selectEmpList = []
        }
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryPageById, params).then((res) => {
          if (res.success) {
            this.model = res.result.records[0]
            this.getSelectUsers(this.formData.dataId)
          }
        })
      }
    },
    // 确定选择
    sureTeam(selectList) {
      this.selectEmpList = selectList
    },
    // 点击查看团队
    acceptClick() {
      this.$nextTick(() => {
        this.$refs.team.init()
      })
    },
    // 变为已读
    async getToRead() {
      let res = await getAction(this.url.read, {
        empId: this.userInfo().empId,
        noticeId: this.model.id
      })
    },

    beginProcess(record) {
      this.$refs.processConfig.visible = true
      this.$refs.processConfig.formUrl = this.formUrl
      this.$refs.processConfig.formUrlMobile = this.formUrlMobile
      this.$refs.processConfig.flowCode = this.flowCode
      this.$refs.processConfig.edit(record, this.processId, this.beanName)
    },
    // 处理新增or编辑返回的结果
    solveResult(res, val) {
      if (val === 1) {
        this.beginProcess(res.result)
        this.$emit('ok', 'submit', this.model);
      } else {
        this.$message.success(res.message)
        this.$emit('ok', 'draft', this.model);
      }
    },
    handleSuccess() {
      this.$message.success('提交成功！')
      this.$emit('ok')
    },
    // 展示文件
    showModal (item) {
      this.prebtnVisible = true
      this.fileUrl = item
    },
    getPreview() {
      const _self = this
      let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + this.fileUrl
      axios({
        url: url,
        params: {},
        method: 'get',
        responseType: 'blob'
      }).then((res) => {
        res
          .arrayBuffer()
          .then(async (buffer) => {
            const existingPdfBytes = await buffer
            const pdfDoc = await PDFDocument.load(existingPdfBytes)
            _self.addCanvasWatermark(pdfDoc, text)
            // _self.downloadCanvasWatermark(pdfDoc, text)
          })
          .catch((e) => console.error('[Preview Pdf Error]:', e))
      }).catch(() => {
        this.modalLoading = false
      })
    },
    addCanvasWatermark(pdfDoc, text) {
      const _self = this
      // 旋转角度大小
      const rotateAngle = Math.PI / 6;
      // labels是要显示的水印文字，垂直排列
      let labels = new Array();
      labels.push(text);
      const pages = pdfDoc.getPages()
      const size = pages[0].getSize()
      let pageWidth = size.width
      let pageHeight = size.height
      let canvas = document.createElement('canvas')
      let canvasWidth = (canvas.width = pageWidth)
      let canvasHeight = (canvas.height = pageHeight)
      const context = canvas.getContext('2d');
      context.font = '14px Arial';

      // 先平移到画布中心
      context.translate(pageWidth / 2, pageHeight / 2 - 250);
      // 在绕画布逆方向旋转30度
      context.rotate(-rotateAngle);
      // 在还原画布的坐标中心
      context.translate(-pageWidth / 2, -pageHeight / 2);

      // 获取文本的最大长度
      let textWidth = Math.max(...labels.map(item => context.measureText(item).width));

      let lineHeight = 15;
      let fontHeight = 12;
      let positionY;
      let i
      i = 0
      positionY = 0
      while (positionY <= pageHeight) {
        positionY = positionY + lineHeight * 5
        i++
      }
      canvasWidth += Math.sin(rotateAngle) * (positionY + i * fontHeight) // 给canvas加上画布向左偏移的最大距离
      canvasHeight = 2 * canvasHeight
      for (positionY = 0, i = 0; positionY <= canvasHeight; positionY = positionY + lineHeight * 5) {
        // 进行画布偏移是为了让画布旋转之后水印能够左对齐;
        context.translate(-(Math.sin(rotateAngle) * (positionY + i * fontHeight)), 0);
        for (let positionX = 0; positionX < canvasWidth; positionX += 2 * textWidth) {
          let spacing = 0;
          labels.forEach(item => {
            context.fillText(item, positionX, positionY + spacing);
            context.fillStyle = 'rgba(187, 187, 187, .4)'; // 字体颜色
            spacing = spacing + lineHeight;
          })
        }
        context.translate(Math.sin(rotateAngle) * (positionY + i * fontHeight), 0);
        context.restore();
        i++
      }
      let dataUrl = canvas.toDataURL('image/png') // 使用Xhr请求获取图片Blob
      let xhr = new XMLHttpRequest()
      xhr.open('get', dataUrl, true)
      xhr.responseType = 'blob'
      xhr.onload = (res) => {
        this.modalLoading = false // 是否可以继续点击下载
        const imgBlob = res.target.response // 获取Blob图片Buffer
        imgBlob.arrayBuffer().then(async (buffer) => {
          const pngImage = await pdfDoc.embedPng(buffer)
          for (let i = 0; i < pages.length; i++) {
            pages[i].drawImage(pngImage)
          } // 序列化为字节
          const pdfBytes = await pdfDoc.save()
          const URL = window.URL || window.webkitURL
          const href = URL.createObjectURL(new Blob([pdfBytes], { type: 'application/pdf;charset=utf-8' }))
          // _self.wSrc = href
          var link = document.createElement('a')
          link.href = href
          // 模拟点击操作，触发下载
          link.style.display = 'none'
          link.setAttribute('download', this.fileUrl)
          document.body.appendChild(link)
          link.click()
          // 清理资源
          document.body.removeChild(link)
          URL.revokeObjectURL(link)
        })
      }
      xhr.send()
    },
    showFile(item) {
      this.modalShowLoading = true
      let fileType = item.substr(-3)
      let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + encodeURI(item)
      axios({
        url: url,
        params: {},
        method: 'get',
        responseType: 'blob'
      }).then(res => {
        if (fileType === 'pdf') {
          let result = new PreviewPdf({
            blob: res,
            docTitle: item,
            isAddWatermark: true, // 是否需要添加水印
            watermark: { // watermark必填 里面可以不填
              type: 'canvas',
              text: text
            }

          })
          if (result.success()) {
            this.modalShowLoading = false
          }
        } else {
          // location.href = url
          this.modalShowLoading = false
          this.$message.error('非pdf文件不可查看')
        }
      })
    },
    downloadFile () {
      this.modalLoading = true
      this.getPreview()
      // if (!this.printInfo.content) {
      //   this.$message.warn('请输入水印内容!')
      //   return
      // }
      // 创建元素
      // var link = document.createElement('a')
      // link.href = this.wSrc
      // // 模拟点击操作，触发下载
      // link.style.display = 'none'
      // link.setAttribute('download', this.fileUrl)
      // document.body.appendChild(link)
      // link.click()
      // // 清理资源
      // document.body.removeChild(link)
      // URL.revokeObjectURL(link)
      // this.$emit('ok')
      // this.handleWaterCancel()
    },
    submitForm (val) {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          if (that.selectEmpList.length == 0) {
            that.$emit('isLoading')
            return that.$message.error('请选择接收人！');
          }

          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'

            this.getToRead()
          }

          let selectEmpList = JSON.parse(JSON.stringify(this.selectEmpList))

          selectEmpList = selectEmpList.map(rr => {
            return {
              empId: rr.empId,
              empDepartIds: rr.departId,
              username: rr.username,
              realname: rr.realname
            }
          })

          httpAction(httpurl, {
            ...this.model,
            selectEmpList
          }, method).then((res) => {
            if (res.success) {
              that.$emit('isLoading')
              that.$emit('close')
              that.solveResult(res, val)
            } else {
              that.$emit('isLoading')
              that.$message.error(res.message)
            }
          }).catch(() => {
            that.$emit('isLoading');
          }).finally(() => {
            that.confirmLoading = false;
          })
        } else {
          that.$emit('isLoading');
        }
      })
    }
  }
}
</script>
